package com.schoolvisitors;

import com.schoolvisitors.exception.BusinessException;
import com.schoolvisitors.exception.ForbiddenException;
import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 参数格式验证失败
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return ResponseEntity.badRequest().body(ResultBody.body(false, 400, errorMessage) );
    }

    // 业务异常处理
    @ExceptionHandler(BusinessException.class)
    public ResultBody handleBusinessExceptions(BusinessException ex) {
        return ResultBody.fail(ex.getResultCode());
    }

    // 参数异常处理
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentExceptions(IllegalArgumentException ex) {
        log.warn(ex.getMessage());
        return ResponseEntity.badRequest().body(ResultBody.body(false, 400, "请求参数异常"));
    }


    // 请求异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, Object>> handleHttpMessageNotReadableExceptions(Exception ex) {
        log.warn(ex.getMessage());
        return ResponseEntity.badRequest().body(ResultBody.body(false, 400,"客户端请求错误"));
                //new HashMap<>(Map.of("status", false,"message", "客户端请求错误", "code", 400)));
    }

    @ExceptionHandler(ForbiddenException.class)
    public ResponseEntity<Map<String, Object>> handleForbidden(ForbiddenException ex) {
        return ResponseEntity.status(403).body(ResultBody.body(false, 403,"无权限访问"));
    }
}
